<template>
  <div>
    <el-dialog
      :visible="visible"
      :title="title"
      :width="width"
      append-to-body
      @close="close"
      @closed="closed"
    >
      <el-form
        ref="selectDataForm"
        :model="selectDataForm"
        label-width="125px"
        label-suffix=":"
        :rules="rules"
      >
        <h3>{{ $t('destructionLang.dataSelect') }}</h3>
        <el-form-item prop="depotId" :label="$t('depotLang.depot')">
          <template>
            <el-radio-group v-model="selectDataForm.depotId">
              <el-radio
                v-for="item in depotList"
                :key="item.value"
                :label="item.value"
              >{{ item.title }}
              </el-radio>
            </el-radio-group>
          </template>
        </el-form-item>
        <el-form-item :label="$t('regionLang.regionType')" prop="regionTypes">
          <el-checkbox-group
            v-model="selectDataForm.regionTypes"
            style="padding: 5px 15px;"
            @change="handleCheckboxChange"
          >
            <el-checkbox :label="allOption.value">
              {{ $t('all') }}
            </el-checkbox>
            <el-checkbox
              v-for="item in regionTypeOptions"
              :key="item.value"
              :label="item.value"
            >{{ $t('regionLang.' + item.title) }}
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item :label="$t('goodsSKULang.storageLocation')" prop="locationCode">
          <el-input
            v-model="selectDataForm.locationCode"
            :placeholder="$t('pleaseEnter') + $t('locationLang.locationCode')"
            clearable
            style="width: 50%"
          />
        </el-form-item>
        <el-form-item :label="$t('destructionLang.sku')" prop="skuCode">
          <el-input
            v-model="selectDataForm.skuCode"
            :placeholder="$t('pleaseEnter') + $t('destructionLang.sku')"
            clearable
            style="width: 50%"
          />
        </el-form-item>
        <el-form-item :label="$t('harvestLang.customerName')" prop="customerIdName">
          <el-input
            v-model="selectDataForm.customerIdName"
            :placeholder="$t('pleaseEnter') + $t('harvestLang.customerName') + '/' + $t('backOrderLang.userId')"
            clearable
            style="width: 50%"
          />
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            size="small"
            :loading="submitLoading"
            style="margin-left: 30px"
            @click="handleSelect"
          >{{ $t("query") }}</el-button>
        </el-form-item>
        <h3>{{ $t('selectData') }}</h3>
        <el-form-item style="margin-left: -100px">
          <el-table
            :data="seletTable"
            border
            @selection-change="selectDataChange"
          >
            <el-table-column type="selection" align="center" min-width="20" />
            <el-table-column
              prop="locationCode"
              :label="$t('goodsSKULang.storageLocation')"
              min-width="80"
              align="center"
            />
            <el-table-column
              prop="regionName"
              :label="$t('locationLang.depotRegion')"
              min-width="80"
              align="center"
            />
            <el-table-column
              prop="skuCode"
              :label="$t('destructionLang.sku')"
              min-width="80"
              align="center"
            />
            <el-table-column
              prop="goodsName"
              :label="$t('OMSLang.itemCn')"
              min-width="80"
              align="center"
            />
            <el-table-column
              prop="skuNum"
              :label="$t('number')"
              min-width="80"
              align="center"
            />
            <el-table-column
              prop="customerName"
              :label="$t('harvestLang.customerName')"
              min-width="80"
              align="center"
            />
          </el-table>
        </el-form-item>
        <el-row type="flex" justify="start">
          <el-button
            type="primary"
            style="width: 20%; margin-left: 20px"
            @click="handleSelectUp"
          >{{ $t("submit") }}</el-button>
        </el-row>

        <h3>{{ $t('destructList') }}</h3>
        <el-form-item style="margin-left: -100px">
          <el-table
            :data="destructTable"
            border
            @selection-change="destructDataChange"
          >
            <el-table-column type="selection" align="center" min-width="20" />
            <el-table-column
              :label="$t('tableIndex')"
              type="index"
              :index="indexAdd"
              align="center"
              width="80"
            />
            <el-table-column
              prop="locationCode"
              :label="$t('goodsSKULang.storageLocation')"
              min-width="80"
              align="center"
            />
            <el-table-column
              prop="regionName"
              :label="$t('locationLang.depotRegion')"
              min-width="80"
              align="center"
            />
            <el-table-column
              prop="skuCode"
              :label="$t('destructionLang.sku')"
              min-width="80"
              align="center"
            />
            <el-table-column
              prop="goodsName"
              :label="$t('OMSLang.itemCn')"
              min-width="80"
              align="center"
            />
            <el-table-column
              prop="skuNum"
              :label="$t('number')"
              min-width="80"
              align="center"
            />
            <el-table-column
              prop="customerName"
              :label="$t('harvestLang.customerName')"
              min-width="80"
              align="center"
            />
            <el-table-column
              :label="$t('operation')"
              width="100"
              align="center"
              fixed="right"
            >
              <template slot-scope="scope">
                <el-button type="text" @click="handleDelete(scope.row)">
                  {{ $t("delete") }}
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
      </el-form>
      <div slot="footer" style="text-align: center">
        <el-button type="warning" plain size="small" @click="close">{{
          $t("cancel")
        }}</el-button>
        <el-button
          v-if="operation === 1"
          type="primary"
          size="small"
          :loading="submitLoading"
          @click="handleSubmit"
        >{{ $t("submit") }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  depotRegionTypeDict
} from '@/utils/dictData'
import { getDictOptionList, getTitleByValue } from '@/utils/dictUtils'
import { getDepotList } from '@/api/business/depotManage/depot'
import to from 'await-to-js'
import { querySKUList, addInventoryOrder } from '@/api/business/operateManage/invetoryOrder'
export default {
  name: 'DepotForm',
  props: {
    value: {
      type: Number,
      default: undefined
    },
    visible: {
      type: Boolean,
      default: undefined
    },
    operation: {
      type: Number,
      default: 0 // 0查看 1新增 2修改
    },
    title: {
      type: String,
      default: null
    },
    width: {
      type: String,
      default: '70%'
    }
  },
  data() {
    return {
      depotList: [],
      allOption: { value: 'all', title: 'all' },
      regionTypeOptions: getDictOptionList(depotRegionTypeDict), // 分区类型
      selectData: [],
      destructData: [],
      destructTable: [],
      selectTable: [],
      selectDataForm: {
        depotId: null,
        regionTypes: []
      },
      rules: {
        depotId: {
          required: true,
          message: this.$t('pleaseSelect'),
          trigger: 'change'
        },
        regionTypes: {
          required: true,
          message: this.$t('pleaseSelect'),
          trigger: 'change'
        }
      },
      seletTable: [],
      displaySupplyOrderNo: false,
      displayPayCustomer: false,
      displayDemandProvider: false,
      submitLoading: false,
      getTitleByValue: getTitleByValue,
      depotDataForm: {},
      submitParams: {}
    }
  },
  watch: {},
  created() {
    this.getDepotList()
  },
  methods: {
    // 仓库下拉列表
    async getDepotList() {
      const { data } = await getDepotList()
      this.depotList = data
      console.log(data)
    },
    // 查询
    async handleSelect() {
      // 最后检查并移除 "all" 选项，如果必要
      // if (this.selectDataForm.regionTypes.includes(this.allOption.value)) {
      //   this.selectDataForm.regionTypes = this.selectDataForm.regionTypes.filter(item => item !== this.allOption.value)
      // }
      if (!this.selectDataForm.customerIdName) {
        delete this.selectDataForm.customerIdName
      }
      if (!this.selectDataForm.containerCode) {
        delete this.selectDataForm.containerCode
      }
      if (!this.selectDataForm.skuCode) {
        delete this.selectDataForm.skuCode
      }
      if (!this.selectDataForm.locationCode) {
        delete this.selectDataForm.locationCode
      }
      const [err] = await to(this.$refs.selectDataForm.validate())
      if (err === null) {
        if (this.operation === 1) {
          const res = await querySKUList({
            ...this.selectDataForm
          })
          if (!res || res.returnCode !== 10000) return
          this.seletTable = res.data
        }
      }
    },
    // 选择数据-选择数据
    selectDataChange(val) {
      this.selectData = val
    },
    // 销毁列表-选择数据
    destructDataChange(val) {
      this.destructData = val
    },
    // 选择数据-提交
    async handleSelectUp() {
      this.destructTable = this.selectData
    },
    async handleDelete(row) {
      this.$confirm(
        this.$t('delete') + '?',
        this.$t('hint'),
        {
          type: 'warning'
        }
      ).then(() => {
        const index = this.destructTable.indexOf(row)
        if (index !== -1) {
          this.destructTable.splice(index, 1)
          this.$message({
            type: 'success',
            message: this.$t('handleSuccess')
          })
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: this.$t('deleteCancelMessage')
        })
      })
    },
    // 提交
    async handleSubmit() {
      const detailList = this.destructData.map(item => ({
        containerId: item.containerId,
        customerId: item.customerId,
        destroyQty: item.skuNum,
        skuNum: item.skuNum,
        skuId: item.skuId
      }))
      const submitParams = {
        depotId: this.selectDataForm.depotId,
        detail: detailList
      }
      const res = await addInventoryOrder({ ...submitParams })
      if (res.data === null && res.returnCode === 10000) {
        this.$message.success(this.$t('handleSuccess'))
        this.selectDataForm = {
          depotId: null,
          regionTypes: [],
          locationCode: null,
          containerCode: null,
          skuCode: null,
          customerIdName: null,
        }
        this.destructTable = []
        this.seletTable = []
        this.selectData = []
        this.destructData = []
        this.$emit('close')
      } else {
        this.$message.error(res.returnMsg)
      }
      console.log(this.destructData, 'this.destructData')
    },
    async handleCheckboxChange(val) {
      const allSelected = this.selectDataForm.regionTypes.includes(this.allOption.value)
      if (allSelected) {
        this.selectDataForm.regionTypes = [this.allOption.value, ...this.regionTypeOptions.map(item => item.value)]
      } else if (this.selectDataForm.regionTypes.length === 0) {
        this.selectDataForm.regionTypes = []
      } else {
        this.selectDataForm.regionTypes = this.selectDataForm.regionTypes.filter(item => item !== this.allOption.value)
      }
    },
    // 关闭
    close() {
      this.$emit('close')
      console.log('对话框关闭')
    },
    closed() {
      console.log('对话框完全关闭')
    }
  }
}
</script>

<style scoped>
.uploaded-image {
  width: 100px;
  height: 100px;
  object-fit: cover;
  margin-right: 10px;
}
.image-list {
  display: flex;
  flex-wrap: wrap;
}
.custom-descriptions .el-descriptions__label {
  text-align: right;
}
</style>
